﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Business_TableView : Frame.Pages.BasePage, Frame.Pages.IDetailEditManPage<DAL.BLI_Book>
{
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        Frame.Global.GlobalFunctions.SetGridView(this.gridView, false);
        this.gridView.SettingsPager.PageSize = 10;
        lblMsg.Text = DateTime.Today.ToShortDateString() + " " + WebUtility.SolarToChineseLunisolarDate(DateTime.Today);
        if (!IsPostBack && !IsCallback)
        {


            Dictionary<string, SqlParameter> ParamDic = new Dictionary<string, SqlParameter>();
            string sqlstr = "select PeriodName=a.PeriodName + ' ' + BeginTime+'——'+EndTime,a.PeriodID from BI_ConsumePeriod a";
            using (SqlDataReader dr = Frame.Global.GlobalSqlHelper.GetSQLDataReader(sqlstr))
            {
                for (; dr.Read(); )
                {
                    Query_Period.Items.Add(dr["PeriodName"].ToString(), dr["PeriodID"]);
                }
            }
            this.Query_BeginT.Date = DateTime.Today;
            this.Query_Period.SelectedIndex = 0;
            ParamDic.Add("Date", new SqlParameter("@bookdate", this.Query_BeginT.Date));
            ParamDic.Add("Period", new SqlParameter("@Period", Convert.ToInt32(this.Query_Period.Value)));
            using (DAL.CMSDALDataContext DContext = new DAL.CMSDALDataContext())
            {
                DAL.BI_Area[] Areas = DContext.BI_Area.ToArray();
                int i = 0;
                foreach (DAL.BI_Area item in Areas)
                {
                    if (i == 0)
                    {
                        ParamDic.Add("AreaID", new SqlParameter("@AreaID", item.AreaID));
                    }
                    TabArea.Tabs.Add(new DevExpress.Web.ASPxTabControl.Tab()
                    {
                        Index = item.AreaID,
                        VisibleIndex = i,
                        Text = item.AreaName,
                        ToolTip = string.Format("{0}\r\n{1}", item.AreaName, item.Remark),
                        NavigateUrl = string.Format("javascript:grid.PerformCallback('{0}')", item.AreaID)
                    });
                    i++;
                }
            }
            Session["TablesqlParams"] = ParamDic;

        }
        if (IsCallback)
        {
            if (this.Query_BeginT.Date == null)
            {
                this.Query_BeginT.Date = DateTime.Today;
            }
            Dictionary<string, SqlParameter> ParamDic = Session["TablesqlParams"] as Dictionary<string, SqlParameter>;
            ParamDic["Date"] = new SqlParameter("@bookdate", this.Query_BeginT.Date);
            ParamDic["Period"] = new SqlParameter("@Period", Convert.ToInt32(this.Query_Period.Value));
        }
        DDataBind();

    }
    DataTable table;
    public DataTable Table
    {
        get
        {
            if (Session["TablesqlParams"] != null)
            {
                table = Frame.Global.GlobalSqlHelper.ExecuteSQLToDataTable(SqlStrFormat,
                    (Session["TablesqlParams"] as Dictionary<string, SqlParameter>).Values.ToArray());
            }
            return table;
        }
    }
    void DDataBind()
    {
        if (Session["TablesqlParams"] != null)
        {
            gridView.DataSource = Table;
            gridView.DataBind();
            this.Query_Bookno.DataSource = Frame.Global.GlobalSqlHelper.ExecuteSQLToDataTable(BookNoSQlStr,
            (Session["TablesqlParams"] as Dictionary<string, SqlParameter>).Values.ToArray());
            this.Query_Bookno.DataBind();
        }
    }
    #region sql语句
    const string SqlStrFormat = @"SELECT *
                                  FROM (SELECT    States.State,
		                                          Tables.TableID,
		                                          Tables.TableName,
		                                          Tables.PCount,
		                                          Tables.Area_ID,
		                                          Tables.Remark,
                                                  BookNo =  States.BookNo,
                                                  DetailRemark = States.Remark
                                        FROM	  dbo.BI_Tables AS Tables,
	                                (SELECT	Detail.Table_ID,
	                                        Detail.State,
                                            Detail.Remark,
                                            book.BookNo
                                     FROM	dbo.BLI_Book AS book,
	                                        dbo.BLI_BookDetail AS Detail
                                     WHERE	Detail.State<>9 and
                                            book.BookDate>=@bookdate AND book.BookDate<DATEADD (day , 1,@bookdate ) AND
	                                        book.Perid_ID=@Period AND
	                                        book.BookNo = Detail.BookNo) AS States
                                WHERE	Tables.TableID=states.Table_ID AND
                                	    Tables.Area_ID=@AreaID
                                UNION 
                                SELECT  State=-1,
		                                  Tables.TableID,
		                                  Tables.TableName,
		                                  Tables.PCount,
		                                  Tables.Area_ID,
		                                  Tables.Remark,
                                          BookNo='',
                                          DetailRemark=''
                                FROM	dbo.BI_Tables AS Tables
                                WHERE	Tables.Area_ID=@AreaID and NOT EXISTS (SELECT  Detail.Table_ID
                                                     FROM	dbo.BLI_Book AS book,
	                                                        dbo.BLI_BookDetail AS Detail
                                                     WHERE	book.BookDate>=@bookdate AND book.BookDate<DATEADD (day , 1,@bookdate ) AND
	                                                        book.Perid_ID=@Period AND
	                                                        book.BookNo = Detail.BookNo AND
	                                                        Tables.TableID=Detail.Table_ID
	                                                        ))  AS tab
	           ORDER BY TableID";
    const string BookNoSQlStr = @"SELECT	AddTime,
	                                        BookNo,
	                                        [Money],
		                                    BookType,
		                                    ContractName,
		                                    ContractPhoneNum
                                FROM	dbo.BLI_Book a
                                WHERE 
                                (EXISTS(
                                SELECT a.BookNo
                                FROM dbo.BLI_BookDetail
                                WHERE  dbo.BLI_BookDetail.State<>9 
                                    ) OR
                                not EXISTS
                                    (
                                SELECT a.BookNo
                                FROM dbo.BLI_BookDetail
                                WHERE a.BookNo= BLI_BookDetail.BookNo
                                    )) and  a.BookDate>=@bookdate AND a.BookDate<DATEADD (day , 1,@bookdate ) AND
	                            a.Perid_ID=@Period
                                    ";

    #endregion

    protected void QueryCBPanel_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        switch (e.Parameter)
        {
            case "btnQuery":
                {
                    DDataBind();
                    break;
                }
            case "btnChange"://转台
                {
                    List<object> objectlist = gridView.GetSelectedFieldValues("TableID");
                    if (objectlist.Count != 2)
                    {
                        DDataBind();
                        throw new Exception("转台必须同时选中2个桌台！");
                    }
                    else
                    {
                        using (DAL.CMSDALDataContext DataSession = new DAL.CMSDALDataContext())
                        {
                            string State_1 = gridView.GetRowValuesByKeyValue(objectlist[0], "State").ToString();
                            string State_2 = gridView.GetRowValuesByKeyValue(objectlist[1], "State").ToString();
                            if (State_1 != "-1" || State_2 != "-1")
                            {
                                string TableID = (State_1 != "-1" ? objectlist[0].ToString() : objectlist[1].ToString());
                                string otherID = (State_1 != "-1" ? objectlist[1].ToString() : objectlist[0].ToString());
                                string BookNo = gridView.GetRowValuesByKeyValue(TableID, "BookNo").ToString();
                                DAL.BLI_BookDetail detail = DataSession.BLI_BookDetail.FirstOrDefault(o => o.BookNo == BookNo && o.Table_ID == TableID);
                                if (detail != null)
                                {
                                    DataSession.BLI_BookDetail.DeleteOnSubmit(detail);
                                    DataSession.BLI_BookDetail.InsertOnSubmit(new DAL.BLI_BookDetail()
                                    {
                                        BookNo = detail.BookNo,
                                        Remark = detail.Remark,
                                        State = detail.State,
                                        Table_ID = otherID
                                    });
                                }
                                TableID = (State_2 != "-1" ? objectlist[0].ToString() : objectlist[1].ToString());
                                otherID = (State_2 != "-1" ? objectlist[1].ToString() : objectlist[0].ToString());
                                BookNo = gridView.GetRowValuesByKeyValue(TableID, "BookNo").ToString();
                                detail = DataSession.BLI_BookDetail.FirstOrDefault(o => o.BookNo == BookNo && o.Table_ID == TableID);
                                if (detail != null)
                                {
                                    DataSession.BLI_BookDetail.DeleteOnSubmit(detail);
                                    DataSession.BLI_BookDetail.InsertOnSubmit(new DAL.BLI_BookDetail()
                                    {
                                        BookNo = detail.BookNo,
                                        Remark = detail.Remark,
                                        State = detail.State,
                                        Table_ID = otherID
                                    });
                                }
                                DataSession.SubmitChanges();
                                DDataBind();
                                this.gridView.Selection.UnselectAll();
                                lblJSmsg.Text = "转台成功！";
                            }
                            else
                            {
                                DDataBind();
                                throw new Exception("桌台均为未预定，无需换台！");
                            }
                        }
                    }
                    break;
                }
            case "btnNew"://新增
                {
                    break;
                }
            case "btnAdd"://追加
                {
                    break;
                }
            default:
                break;
        }


    }
    protected void gridView_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
        Dictionary<string, SqlParameter> ParamDic = Session["TablesqlParams"] as Dictionary<string, SqlParameter>;
        ParamDic["AreaID"] = new SqlParameter("@AreaID", int.Parse(e.Parameters));

        DDataBind();
    }
    protected void lb_Click(object sender, EventArgs e)
    {
        LinkButton lb = sender as LinkButton;
        if (lb.CommandName == "update")
        {

        }

    }
    protected void ConsumerPanel_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        if (!string.IsNullOrEmpty(e.Parameter))
        {
            string[] ary = e.Parameter.Split('|');
            using (DAL.CMSDALDataContext Dcontext = new DAL.CMSDALDataContext())
            {
                DAL.BLI_Book book = Dcontext.BLI_Book.FirstOrDefault(o => o.BookNo == ary[0]);
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                if (book != null)
                {
                    sb.Append("<table width=\"100%\" style=\"font-size: 10pt\">");
                    sb.Append("<tr>");
                    sb.AppendFormat("<td width=\"60px\" style=\"white-space: nowrap\">{0}</td>", "联系人：");
                    sb.AppendFormat("<td style=\"white-space: nowrap\">{0}</td>", book.ContractName);
                    sb.AppendFormat("<td width=\"60px\" style=\"white-space: nowrap\">{0}</td>", "联系电话：");
                    sb.AppendFormat("<td style=\"white-space: nowrap\">{0}</td>", book.ContractPhoneNum);
                    sb.Append("</tr>");
                    sb.Append("<tr>");
                    sb.AppendFormat("<td width=\"60px\" style=\"white-space: nowrap\">{0}</td>", "订金：");
                    sb.AppendFormat("<td colspan=\"3\">{0}</td>", book.Money);
                    sb.Append("</tr>");
                    sb.Append("<tr>");
                    sb.AppendFormat("<td width=\"60px\" style=\"white-space: nowrap\">{0}</td>", "销售人员：");
                    sb.AppendFormat("<td colspan=\"3\">{0}</td>", book.SalesPerson);
                    sb.Append("</tr>");
                    sb.Append("<tr>");
                    sb.AppendFormat("<td width=\"60px\" style=\"white-space: nowrap\">{0}</td>", "备注：");
                    sb.AppendFormat("<td colspan=\"3\">{0}</td>", ary[1]);
                    sb.Append("</tr>");
                    sb.Append("</table>");
                }
                BookDetail.InnerHtml = sb.ToString();
            }
        }
    }

    protected override string ActionID
    {
        get { return "0"; }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        List<object> objList = gridView.GetSelectedFieldValues("BookNo");
        if (objList.Any(o => !string.IsNullOrEmpty(o.ToString())))
        {
            Frame.Global.GlobalFunctions.Alert("所选项中有已经被预定的餐桌！");
        }
        else
        {
            Random ram = new Random();
            DAL.BLI_Book book = new DAL.BLI_Book()
            {
                AddTime = DateTime.Now,
                BookDate = this.Query_BeginT.Date.ToString("yyyy/MM/dd"),
                Perid_ID = Convert.ToInt32(this.Query_Period.SelectedItem.Value),
                BookType = 0,
                BookNo = DateTime.Now.ToString("yyyyMMddhhmmss") + this.Query_Period.SelectedItem.ValueString + ram.Next().ToString()
            };
            using (DAL.CMSDALDataContext DataSession = new DAL.CMSDALDataContext())
            {
                objList = gridView.GetSelectedFieldValues("TableID");
                int Consumerid = -1;
                int.TryParse(Request.QueryString["Consumerid"] ?? "-1", out Consumerid);
                DAL.BI_Consumer consumer = DataSession.BI_Consumer.FirstOrDefault(o => o.ConsumerID == Consumerid);
                if (consumer != null)
                {
                    book.ContractName = consumer.CName;
                    book.ContractPhoneNum = consumer.PhoneNum;
                }
                else
                {
                    book.ContractName = string.Empty;
                    book.ContractPhoneNum = string.Empty;
                }
                DataSession.BLI_Book.InsertOnSubmit(book);
                foreach (object item in objList)
                {
                    DataSession.BLI_BookDetail.InsertOnSubmit(
                        new DAL.BLI_BookDetail() { BookNo = book.BookNo, State = 1, Table_ID = item.ToString() });
                }
                DataSession.SubmitChanges();
            }
            this.Model = book;
            BackUrl = "~/Business/TableView.aspx";
            ScriptBackUrl = "TableView.aspx";
            Frame.Pages.RefrenceContext<DAL.BLI_Book>.UpdateCurrent(this);
            string condiction = string.Empty;
            if (Request.QueryString["Consumerid"] != null)
            {
                condiction = string.Format("&Consumerid={0}", Request.QueryString["Consumerid"]);
            }
            Frame.Global.GlobalFunctions.AlertToUrl("新增成功！现在转入预定界面",
    string.Format("EditBook.aspx?action=new&BookNo={0}{1}", book.BookNo, condiction));
            //Response.Redirect(string.Format("~/Business/EditBook.aspx?action=new{0}",condiction));
        }
    }

    #region IDetailEditManPage<BLI_Book> 成员

    public string BackUrl
    {
        get;
        set;
    }

    public DAL.BLI_Book Model
    {
        get;
        set;
    }

    public string ScriptBackUrl
    {
        get;
        set;
    }

    #endregion
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (this.Query_Bookno.SelectedIndex < 0)
        {
            Frame.Global.GlobalFunctions.Alert("目标订金单号不可为空！");
            return;
        }
        List<object> objList = gridView.GetSelectedFieldValues("BookNo");
        if (objList.Any(o => !string.IsNullOrEmpty(o.ToString())))
        {
            Frame.Global.GlobalFunctions.Alert("所选项中有已经被预定的餐桌！");
        }
        else
        {
            objList = gridView.GetSelectedFieldValues("TableID");
            using (DAL.CMSDALDataContext DataSession = new DAL.CMSDALDataContext())
            {
                foreach (object item in objList)
                {
                    DataSession.BLI_BookDetail.InsertOnSubmit(new DAL.BLI_BookDetail()
                        {
                            BookNo = this.Query_Bookno.SelectedItem.Value.ToString(),
                            State = 1,
                            Table_ID = item.ToString()
                        });
                }
                DataSession.SubmitChanges();
            }
            Frame.Global.GlobalFunctions.AlertToUrl("追加成功！现在转入预定界面",
                string.Format("EditBook.aspx?action=update&BookNo={0}", this.Query_Bookno.SelectedItem.Value));

        }
    }
}